package com.stellar.pay.core.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stellar.pay.config.WxPayConfig;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Base64;

/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/4/4
 * @Description : 微信支付工具类
 */
@Slf4j
@Component
public class WxPayUtil {

    @Resource
    private WxPayConfig wxPayConfig;

    /**
     * 微信支付验签
     *
     * @param message   官方要求的报文
     * @param signature 待验签的签名值
     * @return true/false
     */
    public boolean signatureVerify(String message, String signature) {
        // 将本地的 “微信支付公钥” (pub_key.pem) 读取并转换成 PublicKey 对象
        PublicKey wxChatPayPublicKey = WxPayPublicKeyLoader.loadPublicKey(wxPayConfig.getWxPublicKeyPath());

        try {
            // 解码Base64编码的签名值
            byte[] decodeSignture = Base64.getDecoder().decode(signature);
            // 初始化签名对象
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initVerify(wxChatPayPublicKey);
            sign.update(message.getBytes());
            // 验证签名
            boolean boo = sign.verify(decodeSignture);
            log.info("WxPayUtil.signatureVerify - 验签结果：{}", boo);
            return boo;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA256withRSA 算法不存在");
        } catch (SignatureException e) {
            throw new RuntimeException("签名验证失败");
        } catch (InvalidKeyException e) {
            throw new RuntimeException("SHA256withRSA 算法不存在");
        }
    }

    /**
     * 解密订单信息
     *
     * @param body 密文
     * @return 明文
     */
    public String decryptOrder(String body) {

        try {
            // 将密文转换为Json对象
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(body);
            JsonNode resource = jsonNode.get("resource");

            String associatedData = resource.get("associated_data").asText(); // 关联数据
            String nonce = resource.get("nonce").asText(); // 随机串
            String ciphertext = resource.get("ciphertext").asText(); // 数据密文

            // 创建解密工具AesUtil,用工具解密得到明文
            AesUtil aesUtil = new AesUtil(wxPayConfig.getApiV3Key().getBytes("utf-8"));
            String plainText = aesUtil.decryptToString(associatedData.getBytes("utf-8"),
                    nonce.getBytes("utf-8"),
                    ciphertext);

            return plainText;
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }

    }

}
